<!DOCTYPE html>
<uieip type="page" value="login" debug="true" timeout="5000"></uieip>
<uieip type="reg" value="console"></uieip>

<html>

<head>
    <uieip type="file" value="inc" src="/yqwin/easyui/include.txt" cache="true" minute="1440"></uieip>
    <uieip type="file" value="css" src="/yqwin/css/yqwin.min" cache="false"></uieip>
    <uieip type="file" value="js" src="/yqwin/src/yqwin.min" cache="false"></uieip>
    <title>MdiWin Demo - edit</title>
    <style>
        table.main_tb {
            border-spacing: 0px;
            margin-bottom: 4px;
        }

        table.main_tb>tbody>tr>td,
        table.main_tb>tr>td {
            padding: 0px;
        }
    </style>
</head>

<body>
    <table class="main_tb">
        <tr>
            <td>
                <table id="tb_fields"></table>
            </td>
            <td style="padding-left: 4px;">
                <table id="tb_ui_mask"></table>
            </td>
        </tr>
    </table>
    <div id="tab_set" data-options="border:true" class="easyui-tabs" style="width:100%;height:250px;margin: 0px;">
        <div title="模板" style="padding:0px;display:none;overflow: hidden;">
            <table id="tb_ui"></table>
        </div>
        <div title="关联设置" style="padding:0px;display:none;overflow: hidden;">
            <table id="tb_fk"></table>
        </div>
    </div>
    <script>
        $(function () {
            main_fun.init();
        });

        var page_fun = {
            init: function () {
                $(window).resize(function () {
                    page_fun.resize();
                });
                page_fun.resize();
                uimask_fun.load(2, "{}");
                $("#tab_set").tabs({
                    border: true,
                    onSelect: function (title) {
                        page_fun.tabs_select();
                    }
                });

                main_fun.load_data();
            },
            resize: function () {
                var w = window.innerWidth - 3;
                var h = window.innerHeight - 3;

                var h_2 = h * 0.3;
                if (h_2 < 220) {
                    h_2 = 220;
                }
                var h_1 = h - h_2;

                main_fun.resize({
                    width: w * 0.6,
                    height: h_1
                });
                uimask_fun.resize({
                    width: w - w * 0.6,
                    height: h_1
                });

                w += 3;
                $('#tab_set').tabs("resize", {
                    width: w,
                    height: h_2
                });
                ui_fun.resize({
                    width: w,
                    height: h_2 - 34
                });
                fk_fun.resize({
                    width: w,
                    height: h_2 - 34
                });
            },
            tabs_select: function () {
                var tab = $('#tab_set').tabs('getSelected');
                var index = $('#tab_set').tabs('getTabIndex', tab);
                if (index == 0) {
                    ui_fun.load();
                } else {
                    fk_fun.load();
                }
            }
        }

        var main_fun = {
            id: "tb_fields",
            dbname: null,
            tbname: null,
            tb_id: null,
            tb_row: {},
            init: function () {
                main_fun.dbname = $.urlRequest("dbname");
                main_fun.tbname = $.urlRequest("tbname");
                main_fun.tb_id = $.urlRequest("tb_id");

                var opts = {
                    ajaxUrl: "/_db.html", //ajax地址
                    dbname: main_fun.dbname,   //数据库
                    tbname: "sys_tb_field",
                    keyId: "sid", //关键字段
                    bindingKeyId: "tb_id",
                    bindingValue: main_fun.tb_id,

                    frozenNum: 2,
                    editMode: 1,
                    loadData: false,
                    isPage: false,

                    addWhere: "", //附加条件
                    where: "", //条件
                    order: "queue", //排序

                    isEdit: true, //可编辑
                    copy: true,
                    add: true,
                    upp: true,
                    del: true,
                    isdel: false, //可注销
                    isdelEdit: true, //注销是否可编辑
                    move: true, //可移动
                    toexcel: true, //Excel导出
                    excelName: main_fun.tbname,   //Excel导出文件名
                    beforeToExcel: function (title, rows, callback) { //Excel导出前数据处理
                        var title_ = [];
                        for (var i = 0; i < title.length; i++) {
                            var item = title[i];
                            if (item.name == "name" ||
                                item.name == "ui_title" ||
                                item.name == "fd_type" ||
                                item.name == "length" ||
                                item.name == "decimal" ||
                                item.name == "ui_type_val" ||
                                item.name == "ui_width" ||
                                item.name == "ui_visible" ||
                                item.name == "ui_readonly") {
                                if (item.name == "ui_type_val") {
                                    item.title = item.title.replace("_val", "");
                                }
                                title_.push(item);

                            }
                        }
                        callback(title_, rows);
                    },

                    isSimple: false, //简单查询
                    isSeek: false,  //高级查询
                    editMenus: [{}, {
                        id: "markdown",
                        text: "markdown导出",
                        iconCls: "fa fa-file-code-o",
                    }],
                    editLinks_r: [{
                        id: "delall",
                        text: "全部删除字段",
                        iconCls: "fa fa-trash",
                    }, {
                        id: "load",
                        text: "加载字段信息",
                        iconCls: "fa fa-refresh",
                    }, {}, {
                        id: "viewdata",
                        text: "查看数据",
                        iconCls: "fa fa-table",
                    }],  //右侧附加菜单

                    beforeBindingTitle: function (titles, callback) {
                        for (var i = 0; i < titles.length; i++) {
                            if (titles[i].name == "ui_type") {
                                titles[i].ui_mask.onChange = function (target, value) {
                                    var newval = uimask_fun.get_value();
                                    uimask_fun.load(value, JSON.stringify(newval));
                                };
                            }
                        }
                        //console.log("beforeBindingTitle",titles);
                        callback(titles);
                    }, //标题绑定前
                    afterBindingTitle: function () {
                        page_fun.init();
                    }, //标题绑定后
                    onBeforeEdit: function (index, row) {
                        if (row === null) {
                            uimask_fun.load(2, "{}");
                        } else {
                            uimask_fun.load(row["ui_type"], row["ui_mask"]);
                        }
                    },    //editMode: 1,  自由编辑 生效
                    onAfterEdit: function (index, row, changes) {
                        var row_ = $.extend({}, row);

                        var oldval = row_["ui_mask"];
                        if (oldval === undefined) {
                            oldval = null;
                        }
                        var newval = JSON.stringify(uimask_fun.get_value());
                        if (oldval != newval) {
                            //console.log(oldval,oldval);
                            if (row_["_tag"] != "D" && row_["_tag"] != "A") {
                                row_["_tag"] = "U";
                            }

                            row_["ui_mask"] = newval;
                            $("#" + main_fun.id).yqDataGrid("updateRow", { "index": index, "row": row_ });
                        }
                    },

                    btnAction: function (action, params, callback) {   //头部菜单执行动作，返回true为执行默认选择操作
                        //console.log("btnAction",action);
                        if (action == "markdown") {
                            main_fun.markdown();
                            callback(false);
                        } else if (action == "delall") {
                            main_fun.fields_del_all();
                            callback(false);
                        } else if (action == "load") {
                            main_fun.fields_load();
                            callback(false);
                        } else if (action == "viewdata") {
                            main_fun.dataview();
                            callback(false);
                        } else {
                            callback(true);
                        }
                    },

                    beforeSetdata: function (data, callback) {
                        //console.log(data);
                        callback(data)
                    }, //绑定数据之前
                    afterSetdata: function (data) {
                        page_fun.tabs_select();
                    }, //绑定数据之后
                    beforeSave: function (d_rows, callback) {    //保存前判断
                        if (d_rows.length == 0) {
                            callback(false, d_rows);
                        } else {
                            callback(true, d_rows);
                        }
                    },
                    beforeDataAction: function (d_rows, callback) {    //修改之前，true 执行
                        callback(true, d_rows);
                    },
                };

                $("#" + main_fun.id).yqDataGrid(opts);
            },
            load_data: function () {
                if (!(main_fun.dbname == "" || main_fun.tbname == "" || main_fun.tb_id == "")) {
                    main_fun.get_tb_row(function (res) {
                        if (res.error != 0) {
                            return;
                        }
                        main_fun.tb_row = res.row;

                        $("#" + main_fun.id).yqDataGrid("loadData");
                    });
                }
            },

            get_row: function () {
                return $("#" + main_fun.id).yqDataGrid("getSelected");
            },
            get_index: function () {
                return $("#" + main_fun.id).yqDataGrid("getSelectedIndex");
            },
            update_row: function (row) {
                $("#" + main_fun.id).yqDataGrid("updateRow", { "index": main_fun.get_index(), "row": row });
            },

            options: function () {
                return $("#" + main_fun.id).yqDataGrid("options");
            },
            get_rows: function () {
                return $("#" + main_fun.id).yqDataGrid("getRows");
            },

            resize: function (res) {
                $("#" + main_fun.id).yqDataGrid("resize", res);
            },
            get_tb_row: function (callback) {
                var opts = {
                    dbname: main_fun.dbname,
                    tbname: "sys_tb",
                    keyid: "sid",
                    keyval: main_fun.tb_id
                };

                $.yqDbTbRow(opts, function (res) {
                    callback(res);
                });
            },

            //全部删除字段
            fields_del_all: function () {
                if (main_fun.tbname === null) {
                    return;
                }

                var $object = $("#" + main_fun.id);
                var rows = $object.yqDataGrid("getRows");
                for (var i = rows.length - 1; i >= 0; i--) {
                    $object.yqDataGrid("delRow", i);
                }
            },

            //加载数据库字段
            fields_load: function () {
                if (main_fun.tbname === null) {
                    return;
                }

                var $object = $("#" + main_fun.id);
                $.yqTbFields({
                    dbname: main_fun.dbname,
                    tbname: main_fun.tbname,
                }, function (data) {
                    if (data.error == 0) {
                        var opt = $object.yqDataGrid("options");
                        var rows = $object.yqDataGrid("getRows");
                        for (var i = 0; i < data.rows.length; i++) {
                            var hasRow = false;
                            for (var j = 0; j < rows.length; j++) {
                                if (data.rows[i]["name"] == rows[j]["name"]) {
                                    var row = $.extend({}, rows[j]);
                                    row["fd_type"] = data.rows[i]["fd_type"];
                                    row["length"] = data.rows[i]["length"];
                                    row["decimal"] = data.rows[i]["decimal"];
                                    if (row["_tag"] == undefined || row["_tag"] == "") {
                                        row["_tag"] = "U";
                                    }
                                    $object.yqDataGrid("updateRow", { "index": j, "row": row });

                                    hasRow = true;
                                    break;
                                }
                            }

                            if (!hasRow) {
                                var row = data.rows[i];
                                row["_tag"] = "A";
                                $object.yqDataGrid("appendRow", row);
                            }
                        }

                        $object.yqDataGrid("uppActionState");
                    } else {
                        $.yqMessager("error", data.info);
                    }
                });
            },

            //数据浏览 编辑
            dataview() {
                if (main_fun.tbname === null) {
                    return;
                }

                var prevent_e = { clientX: 0, clientY: 0 };
                var mdiinfo = $.yqGetWindParams();

                var is_move = main_fun.tb_row.is_queue && (
                    (main_fun.tb_row.sys_field === undefined || main_fun.tb_row.sys_field === null) &&
                    (main_fun.tb_row.pid_field === undefined || main_fun.tb_row.pid_field === null)
                );

                var _pops = {
                    title: "dataview",
                    iconCls: "icon2-model-table",
                    onOpen: function ($body) {
                        var w = $body.width();
                        var h = $body.height();
                        $body.append('<table></table>');
                        var $tb = $body.find("table");
                        $tb.width(w);
                        $tb.height(h);

                        $tb.yqDataGrid({
                            ajaxUrl: "/_db.html", //ajax地址
                            dbname: main_fun.dbname,   //数据库
                            tbname: main_fun.tbname,       //表
                            keyId: "sid",       //关键字段
                            bindingKeyId: null,
                            bindingValue: null,
                            pKeyId: null,
                            pKeyValue: null,
                            tempno: -1,

                            addWhere: "",
                            order: "",

                            frozenNum: 2,
                            editMode: 3,
                            editType: 1,
                            editModeW: 500,
                            editModeH: 450,
                            editModeNo: -1,
                            loadData: true,
                            isPage: (!is_move),

                            isEdit: true, //可编辑
                            copy: true,
                            add: true,
                            upp: true,
                            del: true,
                            move: is_move, //可移动
                            //tb_row
                        });
                    },
                    closeBtn: false
                };

                if (window.top == window.self) {
                    var w_ = $(window).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window).height() - 30;

                    $.yqDialog(_pops);
                }
                else {
                    var w_ = $(window.top).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window.top).height() - 30;

                    window.top.$.yqDialog(_pops);
                }
            },
            markdown() {
                var rows = main_fun.get_rows();
                if (rows.length == 0) {
                    $.yqMessager("error", "请先加载字段信息");
                    return;
                }

                var escapeMarkdown = function (text) {
                    // 转义 Markdown 特殊字符
                    return text
                        .replace(/\|/g, "\\|") // 转义 |
                        .replace(/#/g, "\\#") // 转义 #
                        .replace(/\*/g, "\\*") // 转义 *
                        .replace(/_/g, "\\_") // 转义 _
                        .replace(/~/g, "\\~"); // 转义 ~
                }

                // 表头
                let md_tb = "| No. | 字段名 | 标题 | 字段类型 | 备注 |\n";
                md_tb += "| -- | --- | --- | --- | --- |\n";
                // 遍历每一行数据
                rows.forEach((row, index) => {
                    const no = index + 1; // 序号
                    const name = escapeMarkdown(row.name || "");
                    const ui_title = escapeMarkdown(row.ui_title || "");
                    const fd_type = escapeMarkdown(row.fd_type || "");
                    var remark = escapeMarkdown(row.remark?.html || "");
                    if(row.ui_type == 6 || row.ui_type == 13){
                        if(row.ui_mask){
                            var ui_mask_str = "";
                            const ui_mask = JSON.parse(row.ui_mask); 
                            if(ui_mask.lists){
                                ui_mask.lists.forEach((list, index_1) => {
                                    ui_mask_str +=(ui_mask_str==""?"":",")+ `${list.no}:${list.name}`;
                                });
                            }
                            remark+=escapeMarkdown(ui_mask_str);
                        }
                    }

                    md_tb += `| ${no} | ${name} | ${ui_title} | ${fd_type} | ${remark} |\n`;
                });

                console.log(md_tb);

                // 创建下载链接
                const blob = new Blob([md_tb], { type: 'text/markdown;charset=utf-8' });
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                link.download = main_fun.tb_row["name"] + ".md";
                document.body.appendChild(link);
                link.click();
                // 清理
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
            }
        };

        var uimask_fun = {
            id: "tb_ui_mask",
            init: false,
            load: function (ui_type, value) {
                if (uimask_fun.init) {
                    uimask_fun.load_data(ui_type, value);
                    return;
                }
                uimask_fun.init = true;

                $('#' + uimask_fun.id).yqUiMaskEdit({
                    endEdit: function (index, row) {
                        var _row = main_fun.get_row();
                        if (_row == null) {
                            return;
                        }
                        var row_ = $.extend({}, _row);
                        if (row_["_tag"] != "D" && row_["_tag"] != "A") {
                            row_["_tag"] = "U";
                        }
                        row_["ui_mask"] = value = JSON.stringify(uimask_fun.get_value());
                        main_fun.update_row(row_);
                    },
                });

                uimask_fun.load_data(ui_type, value);
            },
            load_data: function (ui_type, value) {
                page_fun.resize();
                $('#' + uimask_fun.id).yqUiMaskEdit("setValue", { "ui_type": ui_type, "value": value });
            },
            get_value: function () {
                if (!uimask_fun.init) {
                    return {};
                }

                return $('#' + uimask_fun.id).yqUiMaskEdit("getValue");
            },
            resize: function (res) {
                if (uimask_fun.init) {
                    $('#' + uimask_fun.id).yqUiMaskEdit("resize", res);
                }
            },
        };

        var ui_fun = {
            id: "tb_ui",
            init: false,
            running: false,
            load: function () {
                if (ui_fun.running) {
                    return;
                }
                ui_fun.running = true;
                if (ui_fun.init) {
                    ui_fun.load_data();
                    return;
                }

                var opts = {
                    ajaxUrl: "/_db.html",
                    dbname: main_fun.dbname,
                    tbname: "sys_tb_ui",
                    keyId: "sid",
                    bindingKeyId: "tb_id",
                    bindingValue: null,

                    addWhere: "",
                    order: "no",

                    editMode: 3,
                    editModeW: 600,
                    editModeH: 450,
                    editModeNo: 1,
                    loadData: false,
                    isPage: false,

                    isEdit: true,
                    copy: true,
                    add: false,
                    upp: false,
                    del: false,
                    isdel: false,
                    isdelEdit: false,
                    move: false,

                    editLinks: [{
                        id: "add1",
                        text: "添加表格",
                        iconCls: "icon2-model-table",
                    }, {
                        id: "add2",
                        text: "添加Html模板",
                        iconCls: "icon2-model-html",
                    }, {
                        id: "add3",
                        text: "代码程序",
                        iconCls: "icon2-model-code",
                    }, {}, {
                        id: "upp",
                        text: "修改",
                        iconCls: "icon2-edit",
                    }, {
                        id: "del",
                        text: "删除",
                        iconCls: "icon2-del",
                    }],

                    isSimple: false,
                    isSeek: false,
                    beforeBindingTitle: function (titles, callback) {
                        for (var i = 0; i < titles.length; i++) {
                            if (titles[i].name == "describe") {
                                titles[i].formatter = function (value, row, index) {
                                    var fun_name = "tb_ui_edit";
                                    if (row["type"] == 1 || row["type"] == 2 || row["type"] == 3) {
                                        return "<a href=\"javascript:ui_fun.edit(" + row["type"] + ",'upp','" + row["sid"] + "');\">" + value + "</a>";
                                    } else {
                                        return value
                                    }
                                }
                                break;
                            }
                        }

                        callback(titles);
                    }, //标题绑定前
                    afterBindingTitle: function () {
                        var opt = $(this).yqDataGrid("options");
                        opt.upp = true;
                        opt.del = true;

                        ui_fun.init = true;

                        ui_fun.load_data();
                    },
                    afterSetdata: function (data) {
                        ui_fun.running = false;
                    }, //绑定数据之后
                    btnAction: function (action, params, callback) {   //头部菜单执行动作，返回true为执行默认选择操作
                        //console.log("btnAction",action);
                        if (action == "copy") {
                            var row = $.extend({}, $(this).yqDataGrid("getSelected"));
                            delete row["sid"];
                            delete row["no"];
                            delete row["describe"];
                            if (row["type"] == 1) {
                                ui_fun.edit1("add", row);
                            } else if (row["type"] == 2) {
                                tb_ui_edit2("add", row);
                            } else if (row["type"] == 3) {
                                tb_ui_edit3("add", row);
                            }
                        }
                        else if (action == "add1") {
                            ui_fun.edit1("add", {});
                        } else if (action == "add2") {
                            ui_fun.edit2("add", {});
                        } else if (action == "add3") {
                            ui_fun.edit3("add", {});
                        } else if (action == "upp") {
                            var row = $(this).yqDataGrid("getSelected");
                            if (row != null) {
                                if (row["type"] == 1) {
                                    ui_fun.edit1("upp", row);
                                } else if (row["type"] == 2) {
                                    ui_fun.edit2("upp", row);
                                } else if (row["type"] == 3) {
                                    ui_fun.edit3("upp", row);
                                }
                            }

                            callback(false);
                        }
                        else if (action == "del") {
                            callback(true);
                        }
                    },
                };

                $("#" + ui_fun.id).yqDataGrid(opts);
            },
            load_data: function () {
                page_fun.resize();

                var opts = ui_fun.options();
                if (main_fun.dbname === opts.dbname &&
                    main_fun.tb_id === opts.bindingValue) {
                    ui_fun.running = false;
                    return;
                }

                opts.dbname = main_fun.dbname;
                opts.bindingValue = main_fun.tb_id;

                $("#" + ui_fun.id).yqDataGrid("loadData");
            },
            options: function () {
                return $("#" + ui_fun.id).yqDataGrid("options");
            },
            resize: function (res) {
                if (ui_fun.init) {
                    $("#" + ui_fun.id).yqDataGrid("resize", res);
                }
            },

            get_rows: function () {
                return $("#" + ui_fun.id).yqDataGrid("getRows");
            },

            data_action: function (action, row) {
                var d_rows = [];
                d_rows.push({ action: action, row: row });
                $("#" + ui_fun.id).yqDataGrid("dataAction", d_rows);
            },
            edit: function (type, action, sid) {
                var rows = ui_fun.get_rows();
                var row = {};
                for (var i = 0; i < rows.length; i++) {
                    if (rows[i].sid == sid) {
                        row = rows[i];
                        break;
                    }
                }

                ui_fun["edit" + type](action, row);
            },
            edit1: function (action, row) {
                var $pp = $("#" + ui_fun.id);
                var prevent_e = { clientX: 0, clientY: 0 };
                var mdiinfo = $.yqGetWindParams();

                var p_opt = main_fun.options();
                var titles = [];
                var rows = [];
                var rows_ = main_fun.get_rows();
                var rows_old = [];
                if (typeof row["model"] != "undefined") {
                    rows_old = JSON.parse(row["model"]);
                }

                if (action == "add") {
                    var d_rows = ui_fun.get_rows();
                    if (d_rows.length == 0) {
                        row["no"] = 1;
                    } else {
                        row["no"] = d_rows[d_rows.length - 1]["no"] + 1;
                    }

                    row["describe"] = "";
                }

                if (rows_old.length == 0) {
                    for (var j = 0; j < rows_.length; j++) {
                        var item = {};
                        item["is_func"] = rows_[j]["is_func"];
                        item["name"] = rows_[j]["name"];
                        item["ui_title"] = rows_[j]["ui_title"];
                        item["fd_type"] = rows_[j]["fd_type"];
                        item["length"] = rows_[j]["length"];
                        item["decimal"] = rows_[j]["decimal"];
                        item["func"] = rows_[j]["func"];
                        item["ui_type"] = rows_[j]["ui_type"];
                        item["ui_width"] = rows_[j]["ui_width"];
                        item["ui_visible"] = rows_[j]["ui_visible"];
                        item["ui_readonly"] = rows_[j]["ui_readonly"];
                        item["ui_mask"] = rows_[j]["ui_mask"];

                        rows.push(item);
                    }
                } else {
                    for (var i = 0; i < rows_old.length; i++) {
                        for (var j = 0; j < rows_.length; j++) {
                            if (rows_old[i]["name"] == rows_[j]["name"]) {
                                var item = $.extend({}, rows_old[i]);
                                item["is_func"] = rows_[j]["is_func"];
                                item["ui_title"] = rows_[j]["ui_title"];
                                item["fd_type"] = rows_[j]["fd_type"];
                                item["length"] = rows_[j]["length"];
                                item["decimal"] = rows_[j]["decimal"];
                                item["func"] = rows_[j]["func"];
                                item["ui_type"] = rows_[j]["ui_type"];
                                item["ui_mask"] = rows_[j]["ui_mask"];

                                rows.push(item);
                                break;
                            }
                        }
                    }

                    for (var j = 0; j < rows_.length; j++) {
                        var hasitem = false;
                        for (var i = 0; i < rows_old.length; i++) {
                            if (rows_[j]["name"] == rows_old[i]["name"]) {
                                hasitem = true;
                                break;
                            }
                        }

                        if (!hasitem) {
                            var item = {};
                            item["is_func"] = rows_[j]["is_func"];
                            item["name"] = rows_[j]["name"];
                            item["ui_title"] = rows_[j]["ui_title"];
                            item["fd_type"] = rows_[j]["fd_type"];
                            item["length"] = rows_[j]["length"];
                            item["decimal"] = rows_[j]["decimal"];
                            item["func"] = rows_[j]["func"];
                            item["ui_type"] = rows_[j]["ui_type"];
                            item["ui_width"] = rows_[j]["ui_width"];
                            item["ui_visible"] = false;
                            item["ui_readonly"] = rows_[j]["ui_readonly"];
                            item["ui_mask"] = rows_[j]["ui_mask"];

                            rows.push(item);
                        }
                    }
                }

                var rows_ = [];
                for (var i = 0; i < rows.length; i++) {
                    if (rows[i]["ui_visible"]) {
                        rows_.push(rows[i]);
                    }
                }
                for (var i = 0; i < rows.length; i++) {
                    if (!rows[i]["ui_visible"]) {
                        rows_.push(rows[i]);
                    }
                }

                for (var i = 0; i < p_opt.titles.length; i++) {
                    var t = $.extend({}, p_opt.titles[i]);
                    if (t["name"] == "is_func" ||
                        t["name"] == "name" ||
                        t["name"] == "fd_type" ||
                        t["name"] == "length" ||
                        t["name"] == "decimal" ||
                        t["name"] == "func" ||
                        t["name"] == "ui_type" ||
                        t["name"] == "ui_mask"
                    ) {
                        t.ui_readonly = true;
                        titles.push(t);
                    }
                }

                var j = 0;
                titles.splice(3 + j, 0, {
                    "name": "group",
                    "ui_title": "分组名称",
                    "fd_type": "nvarchar",
                    "length": 100,
                    "decimal": 0,
                    "ui_type": 2,
                    "ui_width": 90,
                    "ui_visible": true,
                    "ui_readnnly": false,
                    "ui_mask": {
                        "default": "默认值",
                        "min": 0,
                        "max": 50,
                        "blank": false,
                        "format": null
                    }
                });
                j++;
                for (var i = 0; i < p_opt.titles.length; i++) {
                    var t = $.extend({}, p_opt.titles[i]);
                    if (t["name"] == "ui_title" ||
                        t["name"] == "ui_width" ||
                        t["name"] == "ui_visible" ||
                        t["name"] == "ui_readonly"
                    ) {
                        t.ui_readonly = false;
                        titles.splice(3 + j, 0, t);
                        j++;
                    }
                }

                var _pops = {
                    title: "表格",
                    horizontalAlign: "right",
                    onOpen: function ($body) {
                        $body.css({
                            "overflow": "hidden"
                        });

                        var w = $body.width();
                        var h = $body.height();
                        $body.append(`
                        <table style="width:100%;">
                            <tr>
                                <td width="160px;" style="padding:4px 0px 3px 5px;">
                                    <input name="txt_no" style="width:140px;"/>
                                </td>  
                                <td style="padding:4px 0px 3px 5px;">
                                    <input name="txt_describe" style="width:220px;"/>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="4" style="padding:0px">
                                    <div name="txt_model"></div>
                                </td>
                            </tr>
                        </table>
                    `);

                        var $no = $body.find("[name='txt_no']");
                        var $describe = $body.find("[name='txt_describe']");
                        var $tb = $body.find("[name='txt_model']");

                        $no.numberspinner({
                            label: "编码",
                            labelWidth: 35,
                            labelPosition: "before",
                            min: 0,
                            max: 9999,
                            value: row["no"]
                        });

                        $describe.textbox({
                            label: "描述",
                            labelWidth: 35,
                            labelPosition: "before",
                            value: row["describe"]
                        });

                        $tb.yqTableEdit({
                            ajaxUrl: "",
                            titles: titles,  //数据列配置对象
                            rows: rows_,
                            editModeW: w, //模态编辑器宽度 格式为 800（数字）
                            editModeH: h - 79, //模态编辑器高度 格式为 600（数字）
                            isEdit: true,
                            isAdd: false,
                            isDel: false,
                            beforeAdd: function (rows, row, callback) {
                                callback(row);
                            },
                        });
                    },
                    buttons: [{
                        text: "确定",
                        iconCls: 'icon-ok',
                        onClick: function ($body) {
                            var $no = $body.find("[name='txt_no']");
                            var $describe = $body.find("[name='txt_describe']");
                            var $tb = $body.find("[name='txt_model']");

                            var rows = $tb.yqTableEdit("getRows");
                            row = $.extend({}, row);
                            row["tb_id"] = main_fun.tb_id;
                            row["type"] = 1;
                            row["no"] = $no.val();
                            row["describe"] = $describe.val();
                            row["model"] = JSON.stringify(rows);

                            ui_fun.data_action(action, row);

                            this.dialog("close");
                        }
                    }],
                };

                if (window.top == window.self) {
                    var w_ = $(window).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window).height();

                    $.yqDialog(_pops);
                }
                else {
                    var w_ = $(window.top).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window.top).height();

                    window.top.$.yqDialog(_pops);
                }
            },
            edit2: function (action, row) {
                var titles_ = $.yqFmUiTitle(main_fun.get_rows());
                if (action == "add") {
                    var d_rows = ui_fun.get_rows();
                    if (d_rows.length == 0) {
                        row["no"] = 1;
                    } else {
                        row["no"] = d_rows[d_rows.length - 1]["no"] + 1;
                    }

                    row["describe"] = "";
                    row["model"] = "";
                    row["type"] = 2;
                }

                var prevent_e = { clientX: 0, clientY: 0 };
                var mdiinfo = $.yqGetWindParams();

                var _pops = {
                    title: "Html模板",
                    horizontalAlign: "right",
                    onOpen: function ($body) {
                        $body.css({
                            "overflow": "hidden"
                        });
                        var w = $body.width();
                        var h = $body.height();
                        $body.append(`
                        <table style="width:100%;">
                            <tr>
                                <td width="160px;" style="padding:4px 0px 3px 5px;">
                                    <input name="txt_no" style="width:140px;"/>
                                </td>  
                                <td style="padding:4px 0px 3px 5px;">
                                    <input name="txt_describe" style="width:220px;"/>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="4" style="padding:0px">
                                    <div name="txt_model" style="width:100%;height:100%;"></div>
                                </td>
                            </tr>
                        </table>
                    `);

                        var $no = $body.find("[name='txt_no']");
                        var $describe = $body.find("[name='txt_describe']");
                        var $tb = $body.find("[name='txt_model']");

                        $no.numberspinner({
                            label: "编码",
                            labelWidth: 35,
                            labelPosition: "before",
                            min: 0,
                            max: 9999,
                            value: row["no"]
                        });

                        $describe.textbox({
                            label: "描述",
                            labelWidth: 35,
                            labelPosition: "before",
                            value: row["describe"]
                        });

                        $tb.yqTmplHtmlEdit({
                            isEdit: true,
                            width: w,
                            height: h - 79,
                            titles: titles_,
                            value: row["model"]
                        });
                    },
                    buttons: [{
                        text: "确定",
                        iconCls: 'icon-ok',
                        onClick: function ($body) {
                            var $no = $body.find("[name='txt_no']");
                            var $describe = $body.find("[name='txt_describe']");
                            var $tb = $body.find("[name='txt_model']");

                            var value_ = $tb.yqTmplHtmlEdit("getValue");

                            row = $.extend({}, row);
                            row["tb_id"] = main_fun.tb_id;
                            row["no"] = $no.val();
                            row["describe"] = $describe.val();
                            row["model"] = value_;

                            ui_fun.data_action(action, row);

                            this.dialog("close");
                        }
                    }],
                };

                if (window.top == window.self) {
                    var w_ = $(window).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window).height();

                    $.yqDialog(_pops);
                }
                else {
                    var w_ = $(window.top).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window.top).height();

                    window.top.$.yqDialog(_pops);
                }
            },
            edit3: function (action, row) {
                var titles_ = $.yqFmUiTitle(main_fun.get_rows());
                if (action == "add") {
                    var d_rows = ui_fun.get_rows();
                    if (d_rows.length == 0) {
                        row["no"] = 1;
                    } else {
                        row["no"] = d_rows[d_rows.length - 1]["no"] + 1;
                    }

                    row["describe"] = "";
                    row["model"] = "";
                    row["type"] = 3;
                }

                var prevent_e = { clientX: 0, clientY: 0 };
                var mdiinfo = $.yqGetWindParams();

                var _pops = {
                    title: "Code编辑",
                    horizontalAlign: "right",
                    onOpen: function ($body) {
                        $body.css({
                            "overflow": "hidden"
                        });

                        var w = $body.width();
                        var h = $body.height();
                        $body.append(`
                        <table style="width:100%;">
                            <tr>
                                <td width="160px;" style="padding:4px 0px 3px 5px;">
                                    <input name="txt_no" style="width:140px;"/>
                                </td>  
                                <td style="padding:4px 0px 3px 5px;">
                                    <input name="txt_describe" style="width:220px;"/>
                                </td>
                            </tr>
                            <tr>
                                <td colspan="4" style="padding:0px">
                                    <textarea name="txt_model" style="width:100%;height:100%;"></textarea>
                                </td>
                            </tr>
                        </table>
                    `);

                        var $no = $body.find("[name='txt_no']");
                        var $describe = $body.find("[name='txt_describe']");
                        var $tb = $body.find("[name='txt_model']");

                        $no.numberspinner({
                            label: "编码",
                            labelWidth: 35,
                            labelPosition: "before",
                            min: 0,
                            max: 9999,
                            value: row["no"]
                        });

                        $describe.textbox({
                            label: "描述",
                            labelWidth: 35,
                            labelPosition: "before",
                            value: row["describe"]
                        });

                        var model = row["model"];
                        var m_type = "javascript";
                        var m_value = "";
                        if (!(model === undefined || model === null || model == "")) {
                            model = JSON.parse(model);
                            m_type = model.type;
                            m_value = model.value;
                        }

                        $tb.yqCodeEdit({
                            types: ["html", "js", "css"],
                            type: m_type,
                            value: m_value,
                            isEdit: true,
                            width: w,
                            height: h - 79,
                            goDocEnd: false,
                        });

                        //$tb.yqTmplHtmlEdit('resize', { 'height': opt.height - 56, 'width': opt.width - 14 });

                    },
                    buttons: [{
                        text: "确定",
                        iconCls: 'icon-ok',
                        onClick: function ($body) {
                            var $no = $body.find("[name='txt_no']");
                            var $describe = $body.find("[name='txt_describe']");
                            var $tb = $body.find("[name='txt_model']");

                            var value_ = {
                                type: $tb.yqCodeEdit("getType"),
                                value: $tb.yqCodeEdit("getValue")
                            };

                            row = $.extend({}, row);
                            row["tb_id"] = main_fun.tb_id;
                            row["no"] = $no.val();
                            row["describe"] = $describe.val();
                            row["model"] = JSON.stringify(value_);

                            ui_fun.data_action(action, row);

                            this.dialog("close");
                        }
                    }],
                };

                if (window.top == window.self) {
                    var w_ = $(window).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window).height();

                    $.yqDialog(_pops);
                }
                else {
                    var w_ = $(window.top).width();
                    if (w_ > 1200) {
                        w_ = 1200;
                    }
                    _pops.width = w_;
                    _pops.height = $(window.top).height();

                    window.top.$.yqDialog(_pops);
                }
            }
        };

        var fk_fun = {
            id: "tb_fk",
            init: false,
            running: false,
            load: function () {
                if (fk_fun.running) {
                    return;
                }
                fk_fun.running = true;
                if (fk_fun.init) {
                    fk_fun.load_data();
                    return;
                }

                var opts = {
                    ajaxUrl: "/_db.html",
                    dbname: main_fun.dbname,
                    tbname: "sys_tb_fk",
                    keyId: "sid",
                    bindingKeyId: "tb_id",
                    bindingValue: null,

                    addWhere: "",
                    order: "queue",

                    editMode: 3,
                    editModeW: 600,
                    editModeH: 450,
                    editModeNo: 1,
                    loadData: false,
                    isPage: false,

                    isEdit: true,
                    copy: true,
                    add: true,
                    upp: true,
                    del: true,
                    isdel: false,
                    isdelEdit: false,
                    move: true,

                    isSimple: false,
                    isSeek: false,

                    afterBindingTitle: function () {
                        fk_fun.init = true;
                        fk_fun.load_data();
                    },
                    afterSetdata: function (data) {
                        fk_fun.running = false;
                    }, //绑定数据之后
                };

                $("#" + fk_fun.id).yqDataGrid(opts);
            },
            load_data: function () {
                page_fun.resize();

                var opts = fk_fun.options();
                if (main_fun.dbname === opts.dbname &&
                    main_fun.tb_id === opts.bindingValue) {
                    fk_fun.running = false;
                    return;
                }

                opts.dbname = main_fun.dbname;
                opts.bindingValue = main_fun.tb_id;

                $("#" + fk_fun.id).yqDataGrid("loadData");
            },
            options: function () {
                return $("#" + fk_fun.id).yqDataGrid("options");
            },
            resize: function (res) {
                if (fk_fun.init) {
                    $("#" + fk_fun.id).yqDataGrid("resize", res);
                }
            },
        };
    </script>
</body>

</html>